package com.offcn.search.controller;

import com.offcn.entity.Page;
import com.offcn.search.feign.SearchSkuFeign;
import com.offcn.search.pojo.SkuInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author ld
 * @date 2021/9/16 16:17
 */
@Controller
@RequestMapping("/skusearch")
public class SearchController {

   @Resource
    private SearchSkuFeign searchSkuFeign;

    @GetMapping("/searchList")
    public String searchList(@RequestParam(required = false) Map<String,String> searchMap, Model model) {
        System.out.println("---searchMap==--"+searchMap);
        //前端传入搜索条件
        Map<String, Object> result = (Map<String, Object>) searchSkuFeign.search(searchMap).getData();
        Page<SkuInfo> skuInfoPage = new Page<>(
                Long.valueOf(result.get("total").toString()),
                Integer.valueOf(result.get("pageNum").toString()),
                Integer.valueOf(result.get("pageSize").toString())
        );
        model.addAttribute("page", skuInfoPage);
        model.addAttribute("result", result);
        //后台返回搜索条件
        model.addAttribute("searchMap", searchMap);
        //拼接url
        String url = this.setUrl(searchMap);
        model.addAttribute("url", url);
        return "search";
    }

    private String setUrl(Map<String, String> searchMap) {
        String url = "/skusearch/searchList";
        if (searchMap != null && searchMap.size() > 0) {
            url += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                //keywords,brand,category
                String key = entry.getKey();
                //华为
                String value = entry.getValue();
                if (entry.getKey().equals("sortRule") || entry.getKey().equals("sortField")) {
                    continue;
                }
                if (entry.getKey().equals("pageNum")) {
                    continue;
                }
                url += key + "=" + value + "&";
            }
            //去掉多余的&
            if (url.lastIndexOf("&") != -1) {
                url = url.substring(0, url.lastIndexOf("&"));
            }
        }
        System.out.println("--------url-----"+url);
        return url;
    }
}
